import pymysql
from setenv import setLotteryDir
from setenv import getFileDir
from setenv import getFileName
from read_mysql_lottery import save_mysql_lottery
from read_mysql_lottery import get_new_num_periods


def load_sj():
    # 创建数据库连接
    setLotteryDir()
    sjdir = getFileDir()
    sjname = getFileName("sjfilename")
    # 使用上下文管理器打开文件
    with open( str(sjdir) + "/" + str(sjname) , "r") as file:
    # 写入数据

        sjnumarray = file.readlines()
    file.close

    for line in sjnumarray:
        sjnum = []
        sjnum = line.strip('\n').split(' ')
        print("读取文件:"+str(sjnum))
        # for i in range(0,10):
        #     print(sjnum[i])
        if str(sjnum[0]) == "new" :

            print("从数据库中获取最新日期及期号")
            getnnp = get_new_num_periods(sjnum[2],0)
            sjnum[0] = getnnp[0]
            sjnum[1] = getnnp[1]

        sql = "insert into lottery_sj(record_date, num_periods, lottery_type, num1, num2, num3, num4, num5, num6, num7) values(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s);"
        # values = ('2024-03-03','2024023','ssq','10','14','17','19','32','33','6')
        values = (str(sjnum[0]),sjnum[1],sjnum[2],sjnum[3],sjnum[4],sjnum[5],sjnum[6],sjnum[7],sjnum[8],sjnum[9])
        print(sql)
        print("values:"+str(values))
        renum = save_mysql_lottery(sql,values)
        if renum == 0 :
            print("数据存储成功")

        sql = "update lottery_state set state = %s where num_periods = %s;"
        values = (1,sjnum[1])
        print(sql)
        print("values:"+str(values))
        renum = save_mysql_lottery(sql,values)
        if renum == 0 :
            print("数据存储成功")



    return None

if __name__ == '__main__':
    load_sj()
